package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Email;

public class EmailService implements Runnable {
	private Queue<Email> emailQueue = new Queue<>();
	private volatile boolean toBeClosed = false;
	private Thread emailServiceThread;
	
	public EmailService () {
	}

	public void start() {
		emailServiceThread = new Thread(this);
		emailServiceThread.start();
	}
	
	@Override
	public void run() {
		try {
			while (true) {
				sendEmail(emailQueue.pop());
			}
		} catch (InterruptedException e) {
			while (!emailQueue.isEmpty()) {
				try {
					sendEmail(emailQueue.pop());
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	private void sendEmail(Email msg) throws InterruptedException {
		System.out.println("Email sent "+msg.toString());
		Thread.sleep(1500);
	}

	public void addEmailToQueue(Email msg) {
		if (!emailServiceThread.isInterrupted()) {
			emailQueue.push(msg);
		} else {
			System.out.println("Cannot add email to the queue, service is about to shutdown");
		}
	}
	public void stop () {
		toBeClosed = true;
		emailServiceThread.interrupt();
	}

}
